package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;//除了调mapper，有事也可以调service

    /**
     * 营业额统计接口
     */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // 当前集合用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            // 获取当前日期的下一天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 存放每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // 查询date日期对应的营业额,营业额是指状态为已完成的订单金额总和
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map =new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.SumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;// 为了规范，如果turnover为null，则赋值为0.0
            turnoverList.add(turnover);
        }



        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))// 将日期列表转换为字符串，用逗号分隔 lang3包下
                .turnoverList(StringUtils.join(turnoverList, ","))// 将营业额列表转换为字符串，用逗号分隔
                .build();
    }

    /**
     * 指定时间区间内的用户数据统计
     */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 当前集合用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            // 获取当前日期的下一天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 存放用户总量，以逗号分割 select count(*) from user where create_time > begin
        List<Integer> totalUserList = new ArrayList<>();
        // 存放新增用户量，以逗号分割 select count(*) from user where create_time > begin and create_time < end
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();//这里使用Map进行属性的封装，因为这样可以提高代码的泛用性
            map.put("end", endTime);
            // 查询总用户量
            Integer totalUser = userMapper.countByMap(map);
            totalUserList.add(totalUser);
            // 查询新增用户量
            map.put("begin", beginTime);
            Integer newUser = userMapper.countByMap(map);
            newUserList.add(newUser);
        }
        // 返回结果
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))// 将日期列表转换为字符串，用逗号分隔 lang3包下
                .totalUserList(StringUtils.join(totalUserList, ","))// 将用户总量列表转换为字符串，用逗号分隔
                .newUserList(StringUtils.join(newUserList, ","))// 将新增用户列表转换为字符串，用逗号分隔
                .build();

    }

    /**
     * 订单统计接口
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        // 当前集合用于存放从begin到end范围内的每天的日期,以逗号分割
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            // 获取当前日期的下一天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 存放每天的订单总数，以逗号分割
        List<Integer> orderCountList = new ArrayList<>();
        // 存放每天的有效订单数量,以逗号分割
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            // 查询总的订单数列表
            orderCountList.add(orderMapper.countByMap(map));
            map.put("status", Orders.COMPLETED);
            // 查询有效订单数列表
            validOrderCountList.add(orderMapper.countByMap(map));
        }

        // 有效订单数
        int validOrderCount = validOrderCountList.size();
        // 订单总数
        int totalOrderCount = orderCountList.size();
        // 订单完成率
        double orderCompletionRate = validOrderCount / (double) totalOrderCount;

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))// 将日期列表转换为字符串，用逗号分隔 lang3包下
                .orderCountList(StringUtils.join(orderCountList, ","))// 将订单总数列表转换为字符串，用逗号分隔
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))// 将有效订单列表转换为字符串，用逗号分隔
                .totalOrderCount(totalOrderCount)// 总订单数
                .validOrderCount(validOrderCount)// 有效订单数
                .orderCompletionRate(orderCompletionRate)// 订单完成率
                .build();
    }

    /**
     * 查询在begin-end时间段内销量排名前10商品信息
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);


        Map map = new HashMap();
        map.put("begin", beginTime);
        map.put("end", endTime);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(map);
        //通过stream流获取name和number
        List<String> names =salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");

        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");

        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)// 将日期列表转换为字符串，用逗号分隔 lang3包下
                .numberList(numberList)// 将订单总数列表转换为字符串，用逗号分隔
                .build();
    }

    /**导出近30天的运营数据报表
     * @param response
     **/
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //查询概览运营数据，提供给Excel模板文件
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //准备明细数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();

        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
